package com.csrcb.config;

import com.csrcb.filter.TraceIdFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.servlet.ConditionalOnMissingFilterBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * @Classname TraceSleuthConfiguration
 * @Description 过滤器配置类
 * @Date 2021/8/16 13:31
 * @Created by gangye
 */
@Slf4j
@ConditionalOnClass({TraceIdFilter.class})
@ConditionalOnWebApplication
@AutoConfigureAfter(name = {"org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration"})
public class TraceSleuthConfiguration {
    @Bean(
        name = {"traceIdMDCFilterBean"}
    )
    @ConditionalOnMissingBean(
        type = {"org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration"}
    )
    @ConditionalOnMissingFilterBean({TraceIdFilter.class})
    public FilterRegistrationBean<TraceIdFilter> traceIdFilterBean(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TraceIdFilter());
        registration.addUrlPatterns(new String[]{"/*"});
        registration.setOrder(2);//如果有多个过滤器的，设置优先顺序，值越小越先
        registration.setName("traceIdFilter");
        log.info("未检测到[Spring-Sleuth]组件,启用自定义链路追踪器");
        return registration;
    }
}
